package cn.xiaoyao.wx_account.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.xiaoyao.wx_account.enums.WxMpEvent;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Objects;


@Controller
@Slf4j
public class BasicController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @RequestMapping("/wxAccountEvent")
    @ResponseBody
    public Object wxAccountCheck(@RequestParam(value = "signature") String signature,
                                 @RequestParam(value = "timestamp") Long timestamp,
                                 @RequestParam(value = "nonce") String nonce,
                                 @RequestParam(value = "echostr", required = false) String echoStr,
                                 @RequestParam(value = "openid", required = false) String openId,
                                 HttpServletRequest request) throws Exception {

        log.info("signature:{},timestamp:{},nonce:{},echostr:{},openid:{}", signature, timestamp, nonce, echoStr, openId);
        boolean checked = wxMpService.checkSignature(timestamp.toString(), nonce, signature);
        log.info("checked:{}", checked);

        try {
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
            log.info("mpXmlMessage:{}", JSONObject.toJSONString(inMessage));


            String event = inMessage.getEvent();
            String eventKey = inMessage.getEventKey();
            log.info("event:{},eventKey:{}", event, eventKey);

            WxMpEvent wxMpEvent = WxMpEvent.getEventCode(event);
            if (Objects.nonNull(wxMpEvent)) {
                switch (wxMpEvent) {
                    case SCAN:
                        log.info("扫码事件");
                        String uuid = eventKey;
                        log.info("uuid:{}", uuid);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("uuid", uuid);
                        jsonObject.put("logined", true);
                        jsonObject.put("openId", openId);
                        log.info("jsonObject:{}", jsonObject);
                        redisTemplate.opsForValue().set("scaner_login_" + uuid, JSONObject.toJSONString(jsonObject));

                        break;
                    case SUBSCRIBE:
                        log.info("关注事件");
                        String subscribe_uuid = eventKey.split("_")[1];
                        log.info("uuid:{}", subscribe_uuid);
                        JSONObject object = new JSONObject();
                        object.put("uuid", subscribe_uuid);
                        object.put("logined", true);
                        object.put("openId", openId);
                        log.info("jsonObject:{}", object);
                        redisTemplate.opsForValue().set("scaner_login_" + subscribe_uuid, JSONObject.toJSONString(object));
                        break;
                    case UNSUBSCRIBE:
                        log.info("取消关注事件");
                        break;
                    default:
                        log.info("未知事件");
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
        log.info("wxMpUser:{}", wxMpUser);
        return JSONObject.toJSONString(wxMpUser);
        //return echoStr;
    }

    @GetMapping("/generateQrCode")
    @ResponseBody
    public String generateQrCode(@RequestParam(value = "login_uuid") String uuid,
                                 HttpServletResponse response) throws Exception {
        String accessToken = wxMpService.getAccessToken();
        log.info("accessToken:{}", accessToken);
        WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(uuid, 60 * 5);
        String url = wxMpQrCodeTicket.getUrl();
        //使用hutool生成二维码
        QrCodeUtil.generate(url, 300, 300, new File("qrcode.png"));
        //byte[] bytes = QrCodeUtil.generatePng(url, 300, 300);
        String generateAsBase64 = QrCodeUtil.generateAsBase64(url, new QrConfig(300, 300), ImgUtil.IMAGE_TYPE_PNG);
        //response.getOutputStream().write(bytes);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uuid", uuid);
        jsonObject.put("logined", false);
        log.info("jsonObject:{}", jsonObject);
        redisTemplate.opsForValue().set("scaner_login_" + uuid, JSONObject.toJSONString(jsonObject));
        return generateAsBase64;
    }

    @GetMapping("/checkQrCode")
    @ResponseBody
    public boolean checkQrCode(@RequestParam(value = "login_uuid") String uuid) {

        String jsonObject = redisTemplate.opsForValue().get("scaner_login_" + uuid);
        if (Objects.isNull(jsonObject)) {
            return false;
        }
        JSONObject json = JSONObject.parseObject(jsonObject);
        return (Boolean) json.get("logined");
    }


}
